package com.tusuo.stds.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;

import com.tusuo.stds.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;

public class URLImageParser implements Html.ImageGetter {
    Context context;
    View container;
    DisplayMetrics mDisplayMetrics;
    boolean mLimited;

    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param textView
     * @param context
     */
    public URLImageParser(Context context, View textView, boolean limited) {
        this.context = context;
        this.container = textView;
        this.mLimited = limited;

        //最大高度显示为屏幕内容高度的一定比例
        Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
        mDisplayMetrics = new DisplayMetrics();
        display.getMetrics(mDisplayMetrics);
    }

    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
                new ImageGetterAsyncTask(context, urlDrawable);

        asyncTask.execute(source);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        Context context;
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(Context context, URLDrawable d) {
            this.context = context;
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            if (result != null) {
                // set the correct bound according to the result from HTTP call
                urlDrawable.setBounds(0, 0, result.getIntrinsicWidth(), result.getIntrinsicHeight());

                // change the reference of the current drawable to the result
                // from the HTTP call
                urlDrawable.drawable = result;
            }

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();
        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
                if (TextUtils.isEmpty(urlString)) {
                    return null;
                }

                if (urlString.toLowerCase().contains("latex")) {
                    String fileExt = Utils.getFileExtensionFromUrl(urlString);

                    String suffix;

                    if (mDisplayMetrics.density < 3) {
                        suffix = "_200.";
                    } else {
                        suffix = "_250.";
                    }

                    urlString = urlString.substring(0, urlString.lastIndexOf(".")) + suffix + fileExt;
                }

                urlString = Utils.getCorrectImageUrl(urlString);

                String fileString = "";

//                Uri uri = Uri.parse(urlString);
//                String fileString = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + uri.getPath();
//                Timber.d(fileString);
//                Timber.d(urlString);

                Drawable drawable = null;

                //判断SD卡里面是否存在图片文件
//                if (new File(fileString).exists()) {
                if (false) {
                    //获取本地文件返回Drawable
                    drawable = Drawable.createFromPath(fileString);
                    //设置图片边界
                    float multiplier = 20 / (float) drawable.getIntrinsicHeight();
                    int width = (int) (drawable.getIntrinsicWidth() * multiplier);
                    int height = (int) (drawable.getIntrinsicHeight() * multiplier);
                    drawable.setBounds(0, 0, width, height);

                    // 原图片太小
//                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                }else {
                    InputStream is = fetch(urlString);
//                Drawable drawable = Drawable.createFromStream(is, "src");
                    drawable = Drawable.createFromResourceStream(context.getResources(), null, is, null);  //获取网路图片

                    int maxWidth, width;
                    int height;
                    float textHeight = 24 * mDisplayMetrics.density;
                    float scale;

                    if (urlString.toLowerCase().contains("latex")) {
                        // latex图片有放大的版本
                        scale = 1;
                    } else {
                        // 非latex图片，根据网页字体基准的12px，大约乘以设备的密度比
                        scale = mDisplayMetrics.density;
                    }

                    width = (int) (drawable.getIntrinsicWidth() * scale);
                    height = (int) (drawable.getIntrinsicHeight() * scale);

                    // 限制宽度不超过屏幕宽度
                    if (mLimited) {
                        // 选项宽度
                        maxWidth = mDisplayMetrics.widthPixels * 2 / 3;
                    } else {
                        // 正文宽度
                        maxWidth = mDisplayMetrics.widthPixels * 6 / 7;
                    }

                    // 图片高度小于字体高度时，高度需要放大
                    if (height < textHeight) {
                        width = ((int) (width * textHeight)) / height;
                        height = (int) textHeight;
                    }

                    // 超过宽度限制，按比例缩放
                    if (width > maxWidth) {
                        width = maxWidth;
//                        height = height * maxWidth / width; // 按宽度的比例缩放
//                        if (height < textHeight) {
//                            height = (int) textHeight;
//                        }
                    }


//                    if (!urlString.toLowerCase().contains("latex")) {
//                        if (urlString.contains("TS_QuestionImage")) {
//                            maxHeight = 50;
//                        } else {
//                            maxHeight = 32;
//                        }

//                        if (drawable.getIntrinsicHeight() < maxHeight) {
//                            drawable = Utils.Image.zoomDrawable(context.getResources(), drawable,
//                                    width
//                                    , height);
//                        }
//                    }

                    if (drawable.getIntrinsicHeight() != height || drawable.getIntrinsicWidth() != width) {
                        drawable = Utils.Image.zoomDrawable(context.getResources(), drawable, width, height);
                    }

                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
//                    downloadImg(fileString, urlString);
                }

                return drawable;
            } catch (Exception e) {
                return null;
            }
        }

        private boolean downloadImg(String strFile, String imgUrl) {
            final File file = new File(strFile);
            if (file.exists()) {
                file.delete();
            }

            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = fetch(imgUrl);
                if (is == null) {
                    return false;
                }

                byte[] buf = new byte[2048];
                int len;
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return false;
        }

        private InputStream fetch(String urlString) throws IOException {
            OkHttpClient httpClient = new OkHttpClient();
            Request request = new Request.Builder().url(urlString).build();
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().byteStream();
            } else {
                Timber.e(response.toString());
//                Utils.UI.showToastShort("网络不可用！请检查网络设置后重启应用");
                return null;
            }
        }
    }
}
